package com.bsi.core.validate.rule;

/*
 * Author: liusongs
 * Date: 2019/10/25 17:47
 * Content: 非空校验处理类,配合entity上的@Validate注解
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

public class NotNullValidateRule implements ValidateRule {

    private Logger logger = LoggerFactory.getLogger(NotNullValidateRule.class);

    @Override
    public boolean check(Object entity) {
        Assert.notNull(entity, "[NotNullValidateRuleHandler.check]->参数不能为空！");
        List<Field> allField = this.getAllField(entity.getClass());// 获取当前类的所有属性
        if (CollectionUtils.isEmpty(allField)) {
            return true;
        }
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(entity);
        // 进行非空规则校验
        AtomicBoolean flag = new AtomicBoolean(true);
        allField.stream().forEach(field -> {
            Validate validate = field.getDeclaredAnnotation(Validate.class); // 判断当前类上的属性上是否有validate这个注解
            if (validate != null) {
                Class<? extends ValidateRule>[] value = validate.value();
                if (Objects.nonNull(value) && validate.value().length > 0) { // 对有这个注解并且注解值为非空校验的进行属性校验
                    List<Class<? extends ValidateRule>> classes = Arrays.asList(validate.value());
                    List<String> className = classes.stream().map(a -> a.getName()).collect(Collectors.toList());
                    if (className.contains(this.getClass().getName())) {
                        Object propertyValue = beanWrapper.getPropertyValue(field.getName()); // 获取当前属性的值
                        if (propertyValue == null || (!propertyValue.getClass().isPrimitive() && propertyValue == "")) { //判断引用数据类型 如果当前的值为空 则返回false
                            flag.set(false);
                            logger.error("[NotNullValidateRule.check] 校验出:{}类的{}属性为空", entity.getClass().getName(), field.getName());
                        }
                    }
                }
            }
        });
        return flag.get();
    }

    @Override
    public boolean checkField(Object entity, Field field) {
        try {
            if (field.getType().isPrimitive()) {
                return true;
            }
            field.setAccessible(true);
            //判断引用数据类型 如果当前的值为空 则返回false
            if (Objects.nonNull(field.get(entity))) {
                return true;
            }
        } catch (IllegalAccessException e) {
            logger.error("[NotNullValidateRule.checkField] 转换异常:{}类的{}属性为空,异常信息为:{}", entity.getClass().getName(), field.getName(),e.getLocalizedMessage());
        }
        return false;
    }
}
